// import React, { useRef, FC, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
// import { withRouter } from 'react-router-dom'
// import TableDefined from '@/components/common/tableDefined'
// import Dynamic from '@/api/dynamic'
// import { modalLayoutSm } from '@/config/layout'
// import { Button, Input, DatePicker, Select, Modal, Cascader,Spin, Upload, Table, Form, Steps, Row, Col, Tabs, Card, Radio, message } from 'antd';
// import MyDefineSelect from '@/components/common/myDefineSelect'
// import $axios from '@/utils/axios';
// import { fn } from 'moment'
// import TableDefinedEditCom from '@/components/common/tableDefinedEdit'
// const {Option} = Select;
// const delApiid = 'DMT_1001_3'
// const DataBase: FC = () => {
//   const tableRef: RefType = useRef()
//   const AddComRef: RefType = useRef()
//   const searchConfigList = [
//     // {
//     //   key: 'measureName',
//     //   slot: <Input placeholder="请输入名称" allowClear />,
//     //   rules: [],
//     //   initialValue: ''
//     // }
    
//   ];
  
//   // 新增按钮
//   const AddBtn = () => (
//     <Button className="fr" onClick={add} type="primary">
//       新增
//     </Button>
//   )
//   // 添加
//   const add = () => {
//     AddComRef.current.init()
//   }
//    // 添加
//   const edit = (id) => {
//     AddComRef.current.init(id);
//   }
//   // 删除
//   const del = (id:any) => {
//     Modal.confirm({
//       title: '确认删除？',
      
//       onOk() {
//         // Role.roleDel({
//         //   roleid:record.roleid,
//         //   isFormData:true
//         // }).then(()=>{
//         //   tableRef.current.update();
//         // })
//         Dynamic.getDynamicQuery({
//           apiID:delApiid,
//           apiParam:{
//             tran_task_id:id
//           }
//         }).then((res)=>{
//           tableRef.current.update();
//         })
//       },
//       onCancel() {
//         console.log('Cancel');
//       },
//     });
//   }
//   const columns = [
//       {
//         title: '操作',
//         align: 'left',
//         dataIndex: 'scan',
//         key: 'scan',
//         width: '150px',
//         fixed: 'right',
//         render: (text, record, index) => {
//           return <div>
//           <Button className="btn" onClick={()=>edit(record.id)} size="small">编辑</Button>
//           <Button style={{marginLeft:'10px'}} className="btn" onClick={()=>del(record.id)} size="small">删除</Button>
//         </div>
//         }
//       }
// ]
//   return (
//     <>
//       <div style={{marginBottom:'15px'}}>
//         {/* <BatchDel /> */}
//         <AddBtn />
//       </div>
//       <div>
//       <TableDefined
//         apiFun={Dynamic.getDynamicQuery}
//         columns={columns}
//         ref={tableRef}
//         searchConfigList={searchConfigList}
//         extraProps={{ apiID: 'DMT_1002' }}
//       />
//        <TableDefinedEditCom ref={AddComRef} 
//         apiID="DMT_MNG_01"
//         apiParamMng_id = "DMT_1002_1"
//         addApiId = 'DMT_1002_1'
//         updateApiId = 'DMT_1002_2'
        
//         callback={() => {
//         tableRef.current.update();
//       }} />
//       </div>
      
//     </>
//   )
// }
// export default withRouter(DataBase)





import React, { useRef, FC, forwardRef, useImperativeHandle, useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import TableDefined from '@/components/common/tableDefined'
import Dynamic from '@/api/dynamic'
import { modalLayoutSm } from '@/config/layout'
import { Button, Input, DatePicker, Select, Modal, Cascader,Spin, Upload, Table, Form, Steps, Row, Col, Tabs, Card, Radio, message, Checkbox } from 'antd';
import MyDefineSelect from '@/components/common/myDefineSelect'
import $axios from '@/utils/axios';
import { fn } from 'moment'
import TableDefinedEditCom from '@/components/common/tableDefinedEdit'
import ConfigSet from './config'
import DefineSelect from '@/components/common/tableDefinedEdit/DefineSelect.tsx'
const {Option} = Select;


interface DefinedPageoProps {
  configKey: string;
}
const DefinedPage: FC<DefinedPageoProps> = (props:DefinedPageoProps) => {
  const {configKey=''} = props;
  const config = ConfigSet[configKey];
  const tableRef: RefType = useRef()
  const AddComRef: RefType = useRef()
  const [orderBy,setOrderBy] = useState('');
  const [loading,setLoading] = useState(true);
  const [connector,setconnector] = useState({});
  const [searchConfigList,setsearchConfigList] = useState([]);
  // 新增按钮
  const AddBtn = () => (
    <Button className="fr" onClick={add} type="primary">
      新增
    </Button>
  )
  // 添加
  const add = () => {
    AddComRef.current.init()
  }
  const columns = config.columns;
  const getSearchConfig = ()=>{
    Dynamic.getDynamicQuery({
      apiID:'DMT_MNG_01',
      apiParam:{
          api_id:config.searchApiId
      }
    }).then((res)=>{
      let data = res.data;
      let apiParamStr = data.data['0']['api_param']?data.data['0']['api_param']:'';
      let  apiParam= data.data['0']['api_param']?JSON.parse(data.data['0']['api_param']):{};
      let {paramList = []} = apiParam;
      paramList.map((e,i)=>{

        switch(e.name){
          case "where"://查询条件
            let element = e.element||[];
            let searchConfigListNew = [];

            let connectorNew = {};
            
            element.map((el,il)=>{
              connectorNew[el.feild] = el['connector'];
              let ele =  {
                "key": el.feild,
                // "slot": <Input placeholder={"请输入"+el.label} allowClear />,
                "rules": [],
                // "initialValue": '',
                "label":el.label,
              }
              switch(el.type){
                case 'text':
                  ele['slot'] = <Input placeholder={"请输入"+el.label} allowClear />;
                  break;
                case 'checkbox':
                  ele['slot'] = <Checkbox.Group style={{maxWidth:window.innerWidth/2-100+'px'}}>
                    {
                        el.option.map((ek,ik)=>{
                          return <Checkbox defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Checkbox>
                        })
                    }
                  </Checkbox.Group>
                  break;
                case 'select':
                  if(el?.option_url){
                    if(el.mode=="multiple"){
                      ele['slot'] = <DefineSelect mode='multiple' {...el.option_url}/>
                      ele['initialValue'] = [];
                    }else{
                      ele['slot'] = <DefineSelect {...el.option_url}/>
                    }
                    
                  }else{
                    if(el.mode=="multiple"){
                      ele['slot'] = <Select allowClear mode='multiple' placeholder={'请选择'+el.label} style={{maxWidth:window.innerWidth/2-100+'px',minWidth:'120px'}}>
                      {
                          el.option.map((ek,ik)=>{
                            return <Option defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Option>
                          })
                      } 
                    </Select>
                    }else{
                      ele['slot'] = <Select allowClear placeholder={'请选择'+el.label} style={{maxWidth:window.innerWidth/2-100+'px',minWidth:'120px'}}>
                      {
                          el.option.map((ek,ik)=>{
                            return <Option defaultChecked={ek.checked} key={ik} value={ek.value}>{ek.label}</Option>
                          })
                      }
                    </Select>
                    }
                  }
                  
                 
                default:
                  break;
              }
              searchConfigListNew.push(ele)
              setconnector(connectorNew)
            })
            setsearchConfigList(searchConfigListNew);
           
            break;
          case 'orderBy'://排序
            setOrderBy(e.value);
            break;
          case 'paging'://分页
            break;
        }
      })

      setLoading(false);
    })
    
  }
  useEffect(()=>{
    getSearchConfig();
    window[config.id] = {
      "tableRef":tableRef,
      "AddComRef":AddComRef
    }
  },[])
  return (
    <>
      <div >
        {/* <BatchDel /> */}
        <AddBtn />
      </div>
      <div>
      {
        !loading&&<TableDefined
        apiFun={Dynamic.getDynamicQuery}
        columns={columns}
        ref={tableRef}
        searchConfigList={searchConfigList}
        // search_tran_name
        extraProps={{ apiID: config.extraPropsApiid,apiParam:{'orderBy':orderBy}}}
        beforeSearch={(val: any) => {
          // eslint-disable-next-line no-param-reassign
          val.where = [];
          for(let i in val){
            if(i!='where'&&val[i]&&val[i]['length']>0){
              val.where.push({"feild":i, "connector":connector[i], "value":val[i]})
            }
          }
          for(let i in val){
            if(i!='where'){
              delete val[i];
            }
          }
          
          // eslint-disable-next-line no-param-reassign
          return {}
        }} 
      />
      }
      
      <TableDefinedEditCom ref={AddComRef} 
        apiID={config.editapiID}
        apiParamMng_id = {config.editapiParamMng_id}
        addApiId = {config.addApiId}
        updateApiId = {config.updateApiId}
        detailApiId = {config.detailApiId}
        callback={() => {
        tableRef.current.update();
        }}
      />
      </div>
    </>
  )
}

DefinedPage.defaultProps = {
  configKey:''
}
export default withRouter(DefinedPage)

















